package com.example.sources.handler;

import com.example.sources.Param;

import java.lang.reflect.Parameter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liyuncong
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-11-14
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-11-14                  liyuncong          Created
 */
public abstract class AbstractHandlerBase implements AbstractHandler {

    protected static Map<String, Object> paramValueMappingMap(
        Parameter[] parameters, Object[] values
    ) {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < parameters.length; i++) {
            final Parameter parameter = parameters[i];
            final String name = parameter.getAnnotation(Param.class).value();
            map.put(name, values[i]);
        }
        return map;
    }

    protected static Map<String, Object> parseSql(String sql) {
        final String[] split = sql.split("#");
        List<String> paramsIndex = new ArrayList<>();
        for (int i = 1; i < split.length; i++) {
            final String s = split[i];
            final String param = s.split("}")[0].substring(1);
            paramsIndex.add(i - 1, param);
        }
        Pattern pattern = Pattern.compile("#.*?}");
        Matcher matcher = pattern.matcher(sql);
        final String newSql = matcher.replaceAll("?");
        Map<String, Object> result = new HashMap<>();
        result.put("sql", newSql);
        result.put("params", paramsIndex);
        return result;
    }

    protected static void processSql(
        PreparedStatement statement,
        Map<String, Object> paramValueMappingMap,
        List<String> paramsIndex
    ) {
        for (int i = 0; i < paramsIndex.size(); i++) {
            try {
                statement.setObject(i + 1, paramValueMappingMap.get(paramsIndex.get(i)));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
